package com.photographysharing.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.photographysharing.mapper.FilesMapper;
import com.photographysharing.response.DataResponse;
import com.photographysharing.response.DatasResponse;
import com.photographysharing.response.MessageResponse;
import com.photographysharing.service.FileService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public DataResponse<String> upload(@RequestBody MultipartFile file) throws Exception {
        String res = fileService.upload(file);
        return new DataResponse<>(res,"上传成功!");
    }

    /**
     * 文件下载
     */
    @GetMapping("/{uuid}")
    public void download(@PathVariable String uuid, HttpServletResponse httpServletResponse) throws IOException {
        String[] strings = fileService.getFileAddress(uuid);

        File uploadFile = new File(strings[0] + strings[1]);

        //设置格式 以流的形式传输 filename=设置返回文件名字类型
        httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uuid, "UTF-8") + StrUtil.DOT + strings[1]);
        httpServletResponse.setContentType("application/octet-stream");

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        // 读取数据
        outputStream.write(FileUtil.readBytes(uploadFile));
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 文件预览
     */
    @GetMapping("/shows")
    public void preview( String uuid, HttpServletResponse httpServletResponse) throws IOException {
        String[] strings = fileService.getFileAddress(uuid);
        File uploadFile = new File(strings[0] + strings[1]);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        //读取数据
        outputStream.write(FileUtil.readBytes(uploadFile));
        outputStream.flush();
        outputStream.close();
    }


}
